package ext.acae2.dms.parse.wc9;

import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.fc.PersistenceHelper;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTPropertyVetoException;

import com.ptc.core.foundation.type.server.impl.TypeHelper;
import com.ptc.core.meta.common.TypeIdentifier;

import ext.acae2.dms.bean.DataBean;
import ext.acae2.dms.bean.PartBean;
import ext.acae2.dms.resource.DataExchangeResource;
import ext.acae2.util.IBAUtil;
import ext.acae2.util.QueryUtil;
import ext.acae2.util.VersionUtil;

public class PartFactory {

    private static final Logger LOGGER = LogR.getLogger(PartFactory.class.getName());
    private static final String RESOURCE = DataExchangeResource.class.getName();
    private static PartFactory factory = null;
    
    private PartFactory() {}
    
    /**
     * Singleton Pattern to get factory
     * 
     * @return factory
     */
    public static synchronized PartFactory getInstance() {
        if (factory == null) {
            factory = new PartFactory();
        }
        return factory;
    }
    
    public WTPart createPart(DataBean bean) throws WTPropertyVetoException, RemoteException, WTException {
        LOGGER.debug("> Start createPart");
        
        if (bean instanceof PartBean) {
            return createWTPart(bean);
        }
        
        LOGGER.debug("> End createPart");
        return null;
    }
    
    private WTPart createWTPart(DataBean bean) throws WTPropertyVetoException, WTException, RemoteException {
        LOGGER.debug("> Start createWTPart");
        
        PartBean partBean = (PartBean) bean;
        
        String folderName = "/Default/parts";
        //change productName
        WTPart part = createCommonPartToFolder(
                "WCTYPE|wt.part.WTPart", partBean.getName(), partBean.getNumber(), "CJ-1000AX", folderName,bean.getVersion());
        
        IBAUtil iba = new IBAUtil(part);
        
        Set<String> key = partBean.getMap().keySet();    
		 for (Iterator<String> it = key.iterator(); it.hasNext();) {            
			 String s = (String) it.next(); 
			 try{
				 iba.setIBAValue(s, partBean.getMap().get(s));
			 }catch(Exception e){
				 iba.setIBAValue("remark", partBean.getREMARK()+s+"="+partBean.getMap().get(s)+",");
			 }
		 }
        
        //iba source
        iba.setIBAValue("partSource", WTMessage.getLocalizedMessage(RESOURCE, DataExchangeResource.PART_SOURCE));
        iba.saveIBAHolder(part);
        
        LOGGER.debug("> End createWTPart");
        return part;
    }
    
    @SuppressWarnings("deprecation")
    public WTPart createCommonPartToFolder(
            String type, String name, String number, String productName, String folderName,String version) 
                    throws WTException, WTPropertyVetoException {
        LOGGER.debug("> Start createCommonPartToFolder");
        LOGGER.debug("type: " + type);
        LOGGER.debug("name: " + name);
        LOGGER.debug("number: " + number);
        LOGGER.debug("productName: " + productName);
        LOGGER.debug("folderName: " + folderName);
        
        TypeIdentifier typeId = TypeHelper.getTypeIdentifier(type);
        WTPart part = (WTPart) TypeHelper.newInstance(typeId);
        
        WTContainer product = QueryUtil.getContainerByName(productName);
        
        part.setName(name);
        part.setNumber(number);
        part.setContainer(product);
        
        Folder folder = QueryUtil.getFolder(folderName, WTContainerRef.newWTContainerRef(product));
        if (folder != null) {
            LOGGER.debug("folder exists!");
            FolderHelper.assignLocation(part, folder);
        }
        
        if(StringUtils.isNotBlank(version)){
        	String[] versionArr = version.split("\\.");
        	if(versionArr.length==2){
        		VersionUtil.setVersion(part, versionArr[0]);
				VersionUtil.setIteration(part, versionArr[1]);
        	}else{
        		VersionUtil.setVersion(part, versionArr[0]);
        	}
        }
        
        part = (WTPart) PersistenceHelper.manager.save(part);
        
        LOGGER.debug("> End createCommonPartToFolder");
        return part;
    }
}

